package com.treasure.hunt.main

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.content.res.ColorStateList
import android.os.Build
import android.provider.Settings
import android.view.View
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.*
import com.fm.openinstall.OpenInstall
import com.fm.openinstall.listener.AppInstallAdapter
import com.fm.openinstall.model.AppData
import com.module.lemlin.mode.ViewModeActivity
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.qq.e.ads.splash.SplashAD
import com.qq.e.ads.splash.SplashADListener
import com.qq.e.comm.util.AdError
import com.tbruyelle.rxpermissions3.RxPermissions
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.SchemeData
import com.treasure.hunt.mine.MineConfigActivity
import com.treasure.hunt.mode.SplashViewMode
import com.treasure.hunt.popup.DialogHintPopup
import com.treasure.hunt.popup.DialogProtocolPopup
import kotlinx.android.synthetic.main.activity_splash.*
import java.util.*

class SplashActivity1 : ViewModeActivity<SplashViewMode>() {


    private val protocolHintPopup: DialogProtocolPopup by lazy {
        DialogProtocolPopup(context = this,
            onConfirm = {
                protocolContentPopup.setContentText().showPopupWindow()
                protocolHintPopup.dismiss()
            },
            onCancel = {
                protocolHintPopup.dismiss()
                finish()
            },
            onProtocol = { title, content ->

            })
    }
    private val protocolContentPopup: DialogProtocolPopup by lazy {
        DialogProtocolPopup(context = this,
            onConfirm = {
                SPStaticUtils.put(AppConstance.KEY_NAME_PROTOCOL, true)
                protocolContentPopup.dismiss()
//                viewModel.videoNoReward()
                val rxPermissions = RxPermissions((this))
                rxPermissions.request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE
                ).subscribe { aBoolean ->
                    if (aBoolean) {
                        viewModel.videoNoReward(advertisementType = 1)
                    } else {
                        goToMainActivity()
                    }
                }
            },
            onCancel = {
                SPStaticUtils.put(AppConstance.KEY_NAME_PROTOCOL, false)
                protocolHintPopup.setHintText().showPopupWindow()
                protocolContentPopup.dismiss()
            },
            onProtocol = { title, content ->
                MineConfigActivity.open(activity = this, title = title, name = content)
            })
    }

    override fun viewModel(): SplashViewMode {
        return createViewModel()
    }

    override val layoutResId: Int
        get() = R.layout.activity_splash

    override fun initView() {

        SPStaticUtils.remove("token")

        val only = "${Settings.System.getString(
            contentResolver, Settings.Secure.ANDROID_ID
        )}${Build.FINGERPRINT}"
        SPStaticUtils.put(AppConstance.KEY_NAME_UUID_IMEI, EncryptUtils.encryptMD5ToString(only))

        initOpenInstall()

    }

    private fun initOpenInstall() {
        // 获取安装携带的参数
        OpenInstall.getInstall(object : AppInstallAdapter() {
            override fun onInstall(appData: AppData) {
                // 打印数据便于调试
                LogUtils.e("=====getInstall : installData = $appData")
                // 获取渠道数据
                val channelCode: String = appData.getChannel()
                // 获取自定义数据
                val bindData: String = appData.getData()
                var schemeData: SchemeData? = null
                schemeData = try {
                    GsonUtils.fromJson(bindData, SchemeData::class.java)
                } catch (e: Exception) {
                    null
                }
                if (schemeData == null)
                    return
                val type: String = schemeData.type
                    ?: return
                if (type == "1") {
                    SPStaticUtils.put(AppConstance.KEY_NAME_PARENT_ID, schemeData.cart_id)
                }
            }
        })
    }

    override fun initData() {

        val isAgree: Boolean =
            SPStaticUtils.getBoolean(AppConstance.KEY_NAME_PROTOCOL, (false))
        if (!isAgree) {
            protocolContentPopup.setContentText().showPopupWindow()
        } else {
//            val rxPermissions = RxPermissions((this))
//            rxPermissions.request(
//                Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                Manifest.permission.READ_PHONE_STATE
//            ).subscribe { aBoolean ->
//                if (aBoolean) {
//                    viewModel.videoNoReward()
//                } else {
//                    goToMainActivity()
//                }
//            }

            viewModel.videoNoReward(advertisementType = 1)
        }
    }

    override fun initViewMode() {
        viewModel.isGoToMainActivityLiveData.observe(
            this as LifecycleOwner, Observer { isGoMainActivity ->
                if (!isGoMainActivity)
                    return@Observer
                goToMainActivity()
            })

        viewModel.viewAdLiveData.observe(this as LifecycleOwner, Observer { view ->
            if (view != null && !this@SplashActivity1.isFinishing) {
                splash_container.visibility = View.VISIBLE
                splash_container.removeAllViews()
                splash_container.addView(view)
            } else {
                goToMainActivity()
            }
        })

        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                goToMainActivity()
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val code: String? = response.httpData?.data?.advertising_space
            if (cid == null) {
                goToMainActivity()
            } else if (cid == 1 && !code.isNullOrEmpty()) {
                viewModel.loadSplashAdCSJ(mActivity = this, codeId = code)
            } else if (cid == 2 && !code.isNullOrEmpty()) {
                viewModel.loadSplashAdYLH(
                    mActivity = this,
                    container = splash_container,
                    codeId = code
                )
            }
        })


        viewModel.otherConfigLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast("获取协议发送错误：${response.throwable?.msg}")
                finish()
            }
            if (response.status != Status.SUCCESS) {
                return@Observer
            }
            response.httpData?.data?.let {

            }
        })
    }

    /**
     * 跳转到主页面
     */
    private fun goToMainActivity() {
        val intent = Intent(this as Context, MainActivity::class.java)
        startActivity(intent)
        finish()
    }
}